package com.firefoxking.mysite.controller;

import com.firefoxking.mysite.constant.Types;
import com.firefoxking.mysite.constant.WebConst;
import com.firefoxking.mysite.dao.dto.ContentCond;
import com.firefoxking.mysite.entity.Comment;
import com.firefoxking.mysite.entity.Content;
import com.firefoxking.mysite.entity.Options;
import com.firefoxking.mysite.service.comment.CommentService;
import com.firefoxking.mysite.service.content.ContentService;
import com.firefoxking.mysite.service.meta.MetadataService;
import com.firefoxking.mysite.service.options.OptionsService;
import com.firefoxking.mysite.utils.*;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController extends BaseController{

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

//    @Autowired
//    private Commons commons;

    @Autowired
    private OptionsService optionsService;

    @Autowired
    private ContentService contentService;

    @Autowired
    private CommentService commentService;



    @GetMapping(value = {"/", "/index"})
    public String index(Model model, @RequestParam(value = "limit", defaultValue = "12") int limit) {
        return this.index(model,1, limit);
    }

    @GetMapping(value = "/photo/page/{p}")
    public String index(Model model,
                        @PathVariable(name = "p")
                                int page,
                        @RequestParam(name = "limit", required = false, defaultValue = "9999")
                                    int limit
    ) {
        page = page < 0 || page > WebConst.MAX_PAGE ? 1 : page;
        ContentCond contentCond = new ContentCond();
        // contentCond.setCategory("数据库");
        PageInfo<Content> articles = contentService.getArticlesPagedByCond(contentCond, page, limit);
        model.addAttribute("archives", articles);
        model.addAttribute("active", "work");
        // model.addAttribute("commons", commons);
        return "site/index";
    }

    @GetMapping(value = {"/about", "/about/index"})
    public String getAboutPage(Model model) {
        this.blogBaseData(model);
        // model.addAttribute("commons", commons);
        model.addAttribute("active", "about");
        return "site/about";
    }

    @GetMapping(value = {"/blog", "/blog/index"})
    public String blogIndex(Model model, @RequestParam(value = "limit", defaultValue = "11") int limit) {
        return this.blogIndex(model, 1, limit);
    }

    @GetMapping(value = "/blog/page/{p}")
    public String blogIndex(Model model,
                            @PathVariable(name = "p") int page,
                            @RequestParam(value = "limit", required = false, defaultValue = "9999") int limit) {
        page = page < 0 || page > WebConst.MAX_PAGE ? 1 : page;
        ContentCond contentCond = new ContentCond();
        contentCond.setType(Types.ARTICLE.getType());
        PageInfo<Content> articles = contentService.getArticlesPagedByCond(contentCond, page, limit);
        // model.addAttribute("commons", commons);
        model.addAttribute("active", "blog");
        model.addAttribute("articles", articles);
        return "site/blog";
    }

    @GetMapping(value = {"/blog/article/{cid}", "/photo/article/{cid}"})
    public String getArticleDetails(Model model,
                                    @PathVariable(name = "cid") Integer cid) {
        Content article = contentService.getArticleById(cid);
        this.updateArticleHit(article.getCid(),article.getHits());
        List<Comment> comments = commentService.getCommentsByCid(cid);
        model.addAttribute("comments", comments);
        // model.addAttribute("commons", commons);
        model.addAttribute("article", article);
        model.addAttribute("active", "blog");
        return "site/blog-details";
    }

    private void updateArticleHit(Integer cid, Integer chits) {
        Integer hits = cache.hget("article", "hits");
        if (chits == null) {
            chits = 0;
        }
        hits = null == hits ? 1 : hits + 1;
        if (hits >= WebConst.HIT_EXCEED) {
            Content temp = new Content();
            temp.setCid(cid);
            temp.setHits(chits + hits);
            contentService.updateArticleById(temp);
            cache.hset("article", "hits", 0);
        } else {
            cache.hset("article", "hits", hits);
        }
    }

    @PostMapping(value = {"/blog/comment", "/photo/comment"})
    @ResponseBody
    public APIResponse postComment(HttpServletRequest request, Comment comment,
                                   @RequestParam(name = "_csrf_token", required = true) String _csrf_token) {
        String ref = request.getHeader("Referer");
//        if (StringUtils.isBlank(ref) || StringUtils.isBlank(_csrf_token)) {
//            return APIResponse.fail("访问失败");
//        }

//        String token = cache.hget(Types.CSRF_TOKEN.getType(), _csrf_token);
//        if (StringUtils.isBlank(token)) {
//            return APIResponse.fail("访问失败");
//        }

        if (null == comment.getCid() || StringUtils.isBlank(comment.getContent())) {
            return APIResponse.fail("请输入完整后评论");
        }

        if (StringUtils.isNotBlank(comment.getAuthor()) && comment.getAuthor().length() > 50) {
            return APIResponse.fail("姓名过长");
        }

        if (StringUtils.isNotBlank(comment.getMail()) && !TaleUtils.isEmail(comment.getMail())) {
            return APIResponse.fail("请输入正确的邮箱格式");
        }

        if (StringUtils.isNotBlank(comment.getUrl()) && !PatternKit.isURL(comment.getUrl())) {
            return APIResponse.fail("请输入正确的URL格式");
        }

        if (comment.getContent().length() > 200) {
            return APIResponse.fail("请输入200个字符以内的评论");
        }

//        author = TaleUtils.cleanXSS(author);
//        text = TaleUtils.cleanXSS(text);
//
//        author = EmojiParser.parseToAliases(author);
//        text = EmojiParser.parseToAliases(text);

        String val = IPKit.getIpAddrByRequest(request) + ":" + comment.getCid();
        Integer count = cache.hget(Types.COMMENTS_FREQUENCY.getType(), val);
        if (null != count && count > 0) {
            return APIResponse.fail("您发表评论太快了，请过会再试");
        }
        comment.setIp(request.getRemoteAddr());

        commentService.addComment(comment);
        logger.info(comment.getAuthor() + "正常进行评论" + comment.toString());
        // 设置对每个文章1分钟可以评论一次
        cache.hset(Types.COMMENTS_FREQUENCY.getType(), val, 1, 20);

        return APIResponse.success();
    }
}
